package com.huoxingy.print;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

/**
 * Created by hanxi on 2017/12/23.
 */
@Component
@Slf4j
public class OrderMessageListener implements MessageListener {
    private OrderMessageHandler handler;

    @Override
    public Action consume(Message message, ConsumeContext context) {
        log.info("Received message, id:{}, msgKey:{}", message.getMsgID(), message.getKey());

        try {
            String body = new String(message.getBody(), "utf-8");
            int reconsumeTimes = message.getReconsumeTimes();
            boolean shouldRetry = handler.process(body, message.getMsgID(), message.getKey(), reconsumeTimes);
            return shouldRetry ? Action.ReconsumeLater : Action.CommitMessage;
        } catch (UnsupportedEncodingException e) {
            log.warn("Fail to decode body of message which id is:{}, caused by {}, just ditch this message", message.getMsgID(), e.getMessage());
            return Action.CommitMessage;
        } catch (Exception e) {
            log.error("Fail to consume message which id is:{}", message.getMsgID(), e);
            return Action.ReconsumeLater;
        }
    }

    @Autowired
    public void setHandler(OrderMessageHandler handler) {
        this.handler = handler;
    }
}
